#!/usr/bin/env python3.8
# -*- encoding: utf-8 -*-
'''
@File    :   __init__.py
@Time    :   2021/10/16 21:04:22
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from flask import Flask
import click
from flask_migrate import migrate
from albumy.settings import config
from albumy.blueprints.main import main_bp
from albumy.blueprints.auth import auth_bp
from albumy.blueprints.user import user_bp
from albumy.extensions import db,bootstrap,login_manager,moment,csrf,mail,migrate,dropzone,avatars
from albumy.models import User,Role


def create_app():
    
    app = Flask(__name__)
    # 设置从config中导入设置
    app.config.from_object(config['development'])
    register_blueprints(app)
    register_extensions(app)
    register_shell_context(app)
    register_commands(app)    
    return app

def register_blueprints(app):
    app.register_blueprint(main_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(user_bp)

def register_extensions(app):
    db.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    dropzone.init_app(app)
    avatars.init_app(app)
    migrate.init_app(app, db)


def register_shell_context(app):
    @app.shell_context_processor
    def make_shell_context():
        return dict(db=db, User=User,Role=Role)


def register_commands(app):
    
    @app.cli.command()
    def init():
        """Initialize Albumy."""
        click.echo('Initializing the database...')
        db.create_all()

        click.echo('Initializing the roles and permissions...')
        Role.init_role()

        click.echo('Done.')
    
        
    @app.cli.command()
    @click.option('--user', default=10, help='Quantity of users, default is 10.')
    def forge(user,):
        """Generate fake data."""
        from albumy.fakes import fake_admin,fake_user

        db.drop_all()
        db.create_all()

        #初始化role表
        click.echo('Initializing the roles and permissions...')
        Role.init_role()
        click.echo('Generating the administrator...')
        fake_admin()
        click.echo('Generating %d users...' % user)
        fake_user(user)
        click.echo('Done.')




